package com.xja.shoppingmall.service.impl;

import com.alibaba.fastjson.JSON;
import com.xja.shoppingmall.dao.GoodsRepository;
import com.xja.shoppingmall.entity.Goods;
import com.xja.shoppingmall.goods.GoodsVo;
import com.xja.shoppingmall.service.GoodService;
import com.xja.shoppingmall.vo.CommonResponseVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

/**
 * @author CHENCHEN
 * @title
 * @createTime 2021-12-1520:54
 */
@Slf4j
@Transactional(rollbackFor = Exception.class)
@Service
public class GoodServiceImpl implements GoodService {

    @Autowired
    private GoodsRepository goodsRepository;

    @Override
    public CommonResponseVO updateGoodCount(String token, GoodsVo goodsVo) {
        Goods goods = goodsRepository.findById(goodsVo.getId()).get();
        long beforCount = goods.getGoodsCount();
        if(goods == null || goods.getGoodsCount() - goodsVo.getGoodsCount() <0){
            throw new RuntimeException("未找到该商品或库存不足");
        }
        goods.setGoodsCount(goods.getGoodsCount() - goodsVo.getGoodsCount());
        Goods save = goodsRepository.save(goods);
        log.info("befor, after [{}], [{}]", beforCount, save.getGoodsCount());
        return CommonResponseVO.SUCCESS("unknown",save == null ? false:true);
    }
}
